using System;
using Avalonia;
using Avalonia.Controls; 
using JMClient.Assets.ClientDesignConfig;
using System.IO;
using System.Linq;
using System.Text.Json;
using Avalonia.Media;
using JMClient.Assets;
using Material.Colors;
using Material.Styles.Themes;
using Material.Styles.Themes.Base; 
using Microsoft.Extensions.Logging;
using Prism.Ioc; 
using SizeToContent = JMClient.Assets.ClientDesignConfig.SizeToContent;
using SystemDecorations = JMClient.Assets.ClientDesignConfig.SystemDecorations;
using WindowState = JMClient.Assets.ClientDesignConfig.WindowState;
using WindowTransparencyLevel = JMClient.Assets.ClientDesignConfig.WindowTransparencyLevel;

namespace JMClient.Service;
 

/// <summary>
/// 这里是配置的实现
/// </summary>
public class ConfigService
{
    private readonly string _configPath;
    public DesignConfig.WindowConfig CurrentConfig { get; private set; } = new();
    private AvaloniaWindowConfig AvaloniaWindowConfig { get;  set; } = new();
    private ConfigurationService configuration;
    private readonly ILogInstance _loggerInstance;
    private readonly ILogger<ConfigService> _logger;
    /// <summary>
    /// 这里是服务的初始化 这里主要是获取一些基本的日志或者其他依赖 并对一些内容进行配置 比如设置文件路径等
    /// </summary>
    /// <param name="loggers"></param>
    public ConfigService(ILogInstance loggers)
    {
        _loggerInstance = loggers;
        _logger= LogManagement.GetLogger<ConfigService>(loggers.GetType());
        configuration = new ConfigurationService(_loggerInstance);
        _logger.LogInformation("ConfigService 初始化完成，配置路径: {Path}", _configPath);
        _configPath = FilePath.WindowConfig;
        LoadConfiguration();
    }
    /// <summary>
    /// 这里是将配置文件等内容序列化到类 如果不存在或者其他情况要进行默认配置处理
    /// </summary>
    public void LoadConfiguration()
    {
        AvaloniaWindowConfig = configuration.LoadConfigurationFromFile<AvaloniaWindowConfig>(FilePath.AvaloniaWindowConfig);
    }
    /// <summary>
    /// 这里是具体的保存配置 主要是对类进行修改并将内容保存在静态文件
    /// </summary>
    public void SaveConfiguration()
    {
        configuration.SaveConfigurationToFile(AvaloniaWindowConfig, FilePath.AvaloniaWindowConfig);
    }
    /// <summary>
    /// 根据AvaloniaWindowConfig配置类对窗口进行完整的配置修改
    /// </summary>
    /// <param name="window">要配置的Avalonia窗口实例</param>
    public void ApplyWindowSettings(Avalonia.Controls.Window window)
    {
        if (window == null)
        {
            _logger.LogError("窗口实例为空，无法应用配置");
            return;
        }

        _logger.LogInformation("开始应用Avalonia窗口配置...");

        // 确保配置对象存在
        if (AvaloniaWindowConfig == null)
        {
            _logger.LogWarning("AvaloniaWindowConfig为空，创建默认配置");
            AvaloniaWindowConfig = new AvaloniaWindowConfig();
        }

        try
        {
            // 记录配置应用前的窗口状态
            _logger.LogDebug("配置应用前窗口状态: Position=({X},{Y}), Size={Width}x{Height}, State={State}", 
                window.Position.X, window.Position.Y, window.Width, window.Height, window.WindowState);

            // 按顺序应用配置，确保依赖关系正确
            // 1. 首先应用尺寸配置（影响位置计算）
            ApplySizeSettings(window);
            
            // 2. 应用行为配置（影响窗口状态和权限）
            ApplyBehaviorSettings(window);
            
            // 3. 应用样式配置（影响外观）
            ApplyStyleSettings(window);
            
            // 4. 最后应用位置配置（需要尺寸信息）
            ApplyPositionSettings(window);
            
            // 验证配置应用结果
            ValidateAppliedSettings(window);
            
            _logger.LogInformation("Avalonia窗口配置应用完成");
            _logger.LogDebug("配置应用后窗口状态: Position=({X},{Y}), Size={Width}x{Height}, State={State}", 
                window.Position.X, window.Position.Y, window.Width, window.Height, window.WindowState);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "应用Avalonia窗口配置时发生错误");
            throw; // 重新抛出异常，让调用者知道配置失败
        }
    }

    /// <summary>
    /// 应用窗口尺寸配置
    /// </summary>
    private void ApplySizeSettings(Avalonia.Controls.Window window)
    {
        var sizeConfig = AvaloniaWindowConfig.Size;
        if (sizeConfig == null)
        {
            _logger.LogWarning("尺寸配置为空，跳过尺寸设置");
            return;
        }

        _logger.LogDebug("开始应用尺寸配置...");

        // 设置最小尺寸（必须在设置当前尺寸之前）
        if (sizeConfig.MinWidth > 0)
        {
            window.MinWidth = sizeConfig.MinWidth;
            _logger.LogDebug("设置最小宽度: {MinWidth}", sizeConfig.MinWidth);
        }
        
        if (sizeConfig.MinHeight > 0)
        {
            window.MinHeight = sizeConfig.MinHeight;
            _logger.LogDebug("设置最小高度: {MinHeight}", sizeConfig.MinHeight);
        }

        // 设置最大尺寸
        if (sizeConfig.MaxWidth > 0)
        {
            window.MaxWidth = sizeConfig.MaxWidth;
            _logger.LogDebug("设置最大宽度: {MaxWidth}", sizeConfig.MaxWidth);
        }
        
        if (sizeConfig.MaxHeight > 0)
        {
            window.MaxHeight = sizeConfig.MaxHeight;
            _logger.LogDebug("设置最大高度: {MaxHeight}", sizeConfig.MaxHeight);
        }

        // 设置当前尺寸（在最小/最大尺寸设置之后）
        if (sizeConfig.Width > 0)
        {
            window.Width = sizeConfig.Width;
            _logger.LogDebug("设置窗口宽度: {Width}", sizeConfig.Width);
        }
        
        if (sizeConfig.Height > 0)
        {
            window.Height = sizeConfig.Height;
            _logger.LogDebug("设置窗口高度: {Height}", sizeConfig.Height);
        }

        // 设置内容自适应模式
        var sizeToContent = ConvertToAvaloniaSizeToContent(sizeConfig.SizeToContent);
        window.SizeToContent = sizeToContent;
        _logger.LogDebug("设置内容自适应模式: {SizeToContent}", sizeConfig.SizeToContent);

        _logger.LogDebug("尺寸配置应用完成: {Width}x{Height}, Min: {MinWidth}x{MinHeight}, Max: {MaxWidth}x{MaxHeight}, SizeToContent: {SizeToContent}", 
            sizeConfig.Width, sizeConfig.Height, sizeConfig.MinWidth, sizeConfig.MinHeight, 
            sizeConfig.MaxWidth, sizeConfig.MaxHeight, sizeConfig.SizeToContent);
    }

    /// <summary>
    /// 应用窗口行为配置
    /// </summary>
    private void ApplyBehaviorSettings(Avalonia.Controls.Window window)
    {
        var behaviorConfig = AvaloniaWindowConfig.Behavior;
        if (behaviorConfig == null)
        {
            _logger.LogWarning("行为配置为空，跳过行为设置");
            return;
        }

        _logger.LogDebug("开始应用行为配置...");

        // 设置窗口标题
        if (!string.IsNullOrEmpty(behaviorConfig.Title))
        {
            window.Title = behaviorConfig.Title;
            _logger.LogDebug("设置窗口标题: {Title}", behaviorConfig.Title);
        }

        // 设置窗口权限
        window.CanResize = behaviorConfig.CanResize;
        _logger.LogDebug("设置可调整大小: {CanResize}", behaviorConfig.CanResize);

        window.ShowInTaskbar = behaviorConfig.ShowInTaskbar;
        _logger.LogDebug("设置在任务栏显示: {ShowInTaskbar}", behaviorConfig.ShowInTaskbar);
        
        window.ShowActivated = behaviorConfig.ShowActivated;
        _logger.LogDebug("设置激活显示: {ShowActivated}", behaviorConfig.ShowActivated);
        
        window.Topmost = behaviorConfig.Topmost;
        _logger.LogDebug("设置置顶: {Topmost}", behaviorConfig.Topmost);

        // 设置窗口状态（在权限设置之后）
        var windowState = ConvertToAvaloniaWindowState(behaviorConfig.WindowState);
        window.WindowState = windowState;
        _logger.LogDebug("设置窗口状态: {WindowState}", behaviorConfig.WindowState);

        _logger.LogDebug("行为配置应用完成: Title={Title}, State={WindowState}, CanResize={CanResize}, Topmost={Topmost}", 
            behaviorConfig.Title, behaviorConfig.WindowState, behaviorConfig.CanResize, behaviorConfig.Topmost);
    }

    /// <summary>
    /// 应用窗口样式配置
    /// </summary>
    private void ApplyStyleSettings(Avalonia.Controls.Window window)
    {
        var styleConfig = AvaloniaWindowConfig.Style;
        if (styleConfig == null)
        {
            _logger.LogWarning("样式配置为空，跳过样式设置");
            return;
        }

        _logger.LogDebug("开始应用样式配置...");

        // 设置透明度
        if (styleConfig.Opacity > 0 && styleConfig.Opacity <= 1.0)
        {
            window.Opacity = styleConfig.Opacity;
            _logger.LogDebug("设置窗口透明度: {Opacity}", styleConfig.Opacity);
        }
        else if (styleConfig.Opacity != 1.0)
        {
            _logger.LogWarning("透明度值无效: {Opacity}，使用默认值1.0", styleConfig.Opacity);
        }

        // 设置背景色
        if (!string.IsNullOrEmpty(styleConfig.Background))
        {
            try
            {
                var brush = new SolidColorBrush(Color.Parse(styleConfig.Background));
                window.Background = brush;
                _logger.LogDebug("设置背景色: {Background}", styleConfig.Background);
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "无法解析背景色: {Background}，使用默认背景", styleConfig.Background);
            }
        }

        // 设置系统装饰
        var systemDecorations = ConvertToAvaloniaSystemDecorations(styleConfig.SystemDecorations);
        window.SystemDecorations = systemDecorations;
        _logger.LogDebug("设置系统装饰: {SystemDecorations}", styleConfig.SystemDecorations);

        // 设置扩展客户区
        window.ExtendClientAreaToDecorationsHint = styleConfig.ExtendClientAreaToDecorationsHint;
        _logger.LogDebug("设置扩展客户区到装饰区域: {ExtendClientAreaToDecorationsHint}", 
            styleConfig.ExtendClientAreaToDecorationsHint);
        

        
        if (styleConfig.ExtendClientAreaTitleBarHeightHint > 0)
        {
            window.ExtendClientAreaTitleBarHeightHint = styleConfig.ExtendClientAreaTitleBarHeightHint;
            _logger.LogDebug("设置扩展客户区标题栏高度: {ExtendClientAreaTitleBarHeightHint}", 
                styleConfig.ExtendClientAreaTitleBarHeightHint);
        }

  
        _logger.LogDebug("样式配置应用完成: Opacity={Opacity}, Background={Background}, SystemDecorations={SystemDecorations}", 
            styleConfig.Opacity, styleConfig.Background, styleConfig.SystemDecorations);
    }

    /// <summary>
    /// 应用窗口位置配置
    /// </summary>
    private void ApplyPositionSettings(Avalonia.Controls.Window window)
    {
        var positionConfig = AvaloniaWindowConfig.Position;
        var behaviorConfig = AvaloniaWindowConfig.Behavior;
        
        if (positionConfig == null || behaviorConfig == null)
        {
            _logger.LogWarning("位置配置或行为配置为空，跳过位置设置");
            return;
        }

        _logger.LogDebug("开始应用位置配置...");

        // 根据启动位置设置窗口位置
        switch (behaviorConfig.StartupLocation)
        {
            case JMClient.Assets.ClientDesignConfig.WindowStartupLocation.Manual:
                if (positionConfig.RememberPosition && positionConfig.LastPosition != null)
                {
                    var pos = positionConfig.LastPosition;
                    window.Position = new PixelPoint(pos.X, pos.Y);
                    _logger.LogDebug("应用记忆位置: ({X}, {Y})", pos.X, pos.Y);
                }
                else
                {
                    _logger.LogDebug("未启用位置记忆或没有记忆位置，使用默认位置");
                }
                break;
                
            case JMClient.Assets.ClientDesignConfig.WindowStartupLocation.CenterScreen:
                // 获取主屏幕并居中 这里不再记忆上一次的位置，有需要可以更改
                var screen = window.Screens.Primary;
                if (screen != null)
                {
                    var x = (int)((screen.Bounds.Width - window.Width) / 2);
                    var y = (int)((screen.Bounds.Height - window.Height) / 2);
                    window.Position = new PixelPoint(x, y);
                    _logger.LogDebug("应用屏幕居中位置: ({X}, {Y})，屏幕尺寸: {ScreenWidth}x{ScreenHeight}", 
                        x, y, screen.Bounds.Width, screen.Bounds.Height);
                }
                else
                {
                    _logger.LogWarning("无法获取主屏幕信息，使用默认位置");
                }
                break;
                
            case JMClient.Assets.ClientDesignConfig.WindowStartupLocation.CenterOwner:
                // 如果有所有者窗口，则相对于所有者窗口居中
                if (window.Owner != null)
                {
                    // 注意：Owner.Position 可能不存在，暂时注释掉
                    // var ownerPos = window.Owner.Position;
                    // var ownerSize = window.Owner.ClientSize;
                    // var x = ownerPos.X + (int)((ownerSize.Width - window.Width) / 2);
                    // var y = ownerPos.Y + (int)((ownerSize.Height - window.Height) / 2);
                    // window.Position = new PixelPoint(x, y);
                    // _logger.LogDebug("应用所有者居中位置: ({X}, {Y})，所有者位置: ({OwnerX}, {OwnerY})，所有者尺寸: {OwnerWidth}x{OwnerHeight}", 
                    //     x, y, ownerPos.X, ownerPos.Y, ownerSize.Width, ownerSize.Height);
                    _logger.LogDebug("所有者居中功能暂时禁用，因为 Owner.Position 属性可能不存在");
                }
                else
                {
                    _logger.LogWarning("窗口没有所有者，回退到屏幕居中");
                    // 回退到屏幕居中
                    var fallbackScreen = window.Screens.Primary;
                    if (fallbackScreen != null)
                    {
                        var x = (int)((fallbackScreen.Bounds.Width - window.Width) / 2);
                        var y = (int)((fallbackScreen.Bounds.Height - window.Height) / 2);
                        window.Position = new PixelPoint(x, y);
                        _logger.LogDebug("回退到屏幕居中位置: ({X}, {Y})", x, y);
                    }
                }
                break;
                
            default:
                _logger.LogWarning("未知的启动位置类型: {StartupLocation}，使用默认位置", behaviorConfig.StartupLocation);
                break;
        }

        _logger.LogDebug("位置配置应用完成，最终位置: ({X}, {Y})", window.Position.X, window.Position.Y);
    }

    /// <summary>
    /// 验证应用后的窗口设置
    /// </summary>
    private void ValidateAppliedSettings(Avalonia.Controls.Window window)
    {
        _logger.LogDebug("开始验证应用后的窗口设置...");

        var sizeConfig = AvaloniaWindowConfig.Size;
        var behaviorConfig = AvaloniaWindowConfig.Behavior;
        var styleConfig = AvaloniaWindowConfig.Style;

        // 验证尺寸设置
        if (sizeConfig != null)
        {
            if (sizeConfig.Width > 0 && Math.Abs(window.Width - sizeConfig.Width) > 1)
            {
                _logger.LogWarning("窗口宽度设置可能未生效: 期望={Expected}, 实际={Actual}", 
                    sizeConfig.Width, window.Width);
            }
            
            if (sizeConfig.Height > 0 && Math.Abs(window.Height - sizeConfig.Height) > 1)
            {
                _logger.LogWarning("窗口高度设置可能未生效: 期望={Expected}, 实际={Actual}", 
                    sizeConfig.Height, window.Height);
            }
        }

        // 验证行为设置
        if (behaviorConfig != null)
        {
            if (!string.IsNullOrEmpty(behaviorConfig.Title) && window.Title != behaviorConfig.Title)
            {
                _logger.LogWarning("窗口标题设置可能未生效: 期望={Expected}, 实际={Actual}", 
                    behaviorConfig.Title, window.Title);
            }

            if (window.CanResize != behaviorConfig.CanResize)
            {
                _logger.LogWarning("可调整大小设置可能未生效: 期望={Expected}, 实际={Actual}", 
                    behaviorConfig.CanResize, window.CanResize);
            }

            if (window.Topmost != behaviorConfig.Topmost)
            {
                _logger.LogWarning("置顶设置可能未生效: 期望={Expected}, 实际={Actual}", 
                    behaviorConfig.Topmost, window.Topmost);
            }
        }

        // 验证样式设置
        if (styleConfig != null)
        {
            if (styleConfig.Opacity > 0 && styleConfig.Opacity <= 1.0 && 
                Math.Abs(window.Opacity - styleConfig.Opacity) > 0.01)
            {
                _logger.LogWarning("透明度设置可能未生效: 期望={Expected}, 实际={Actual}", 
                    styleConfig.Opacity, window.Opacity);
            }
        }

        _logger.LogDebug("窗口设置验证完成");
    }

    /// <summary>
    /// 保存当前窗口状态到配置
    /// </summary>
    public void SaveCurrentWindowState(Avalonia.Controls.Window window)
    {
        try
        {
            // 检查窗口位置是否有效
            if (AvaloniaWindowConfig?.Position?.RememberPosition == true)
            {
                var pos = window.Position;
                if (double.IsFinite(pos.X) && double.IsFinite(pos.Y))
                {
                    AvaloniaWindowConfig.Position.LastPosition = new WindowPoint
                    {
                        X = pos.X,
                        Y = pos.Y
                    };
                    _logger.LogDebug("保存窗口位置: ({X}, {Y})", pos.X, pos.Y);
                }
                else
                {
                    _logger.LogWarning("窗口位置无效 (NaN/Infinity)，跳过位置保存");
                }
            }
            
            // 检查窗口尺寸是否有效
            if (AvaloniaWindowConfig?.Position?.RememberSize == true)
            {
                if (double.IsFinite(window.Width) && double.IsFinite(window.Height) && 
                    window.Width > 0 && window.Height > 0)
                {
                    AvaloniaWindowConfig.Size.Width = window.Width;
                    AvaloniaWindowConfig.Size.Height = window.Height;
                    _logger.LogDebug("保存窗口尺寸: {Width}x{Height}", window.Width, window.Height);
                }
                else
                {
                    _logger.LogWarning("窗口尺寸无效 (NaN/Infinity/零值)，跳过尺寸保存");
                }
            }
            
            // 保存窗口状态
            if (AvaloniaWindowConfig?.Position?.RememberState == true)
            {
                AvaloniaWindowConfig.Behavior.WindowState = ConvertFromAvaloniaWindowState(window.WindowState);
                _logger.LogDebug("保存窗口状态: {WindowState}", window.WindowState);
            }
            
            // 更新元数据
            if (AvaloniaWindowConfig?.Metadata != null)
            {
                AvaloniaWindowConfig.Metadata.LastModified = DateTime.Now;
            }
            
            this.SaveConfiguration();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "保存窗口状态时发生错误");
        }
    }

    #region 窗口属性的转换方法

    /// <summary>
    /// 转换为Avalonia的SizeToContent
    /// </summary>
    private static Avalonia.Controls.SizeToContent ConvertToAvaloniaSizeToContent(SizeToContent sizeToContent)
    {
        return sizeToContent switch
        {
            JMClient.Assets.ClientDesignConfig.SizeToContent.Manual => Avalonia.Controls.SizeToContent.Manual,
            JMClient.Assets.ClientDesignConfig.SizeToContent.Width => Avalonia.Controls.SizeToContent.Width,
            JMClient.Assets.ClientDesignConfig.SizeToContent.Height => Avalonia.Controls.SizeToContent.Height,
            JMClient.Assets.ClientDesignConfig.SizeToContent.WidthAndHeight => Avalonia.Controls.SizeToContent.WidthAndHeight,
            _ => Avalonia.Controls.SizeToContent.Manual
        };
    }

    /// <summary>
    /// 转换为Avalonia的WindowState
    /// </summary>
    private static Avalonia.Controls.WindowState ConvertToAvaloniaWindowState(WindowState windowState)
    {
        return windowState switch
        {
            JMClient.Assets.ClientDesignConfig.WindowState.Normal => Avalonia.Controls.WindowState.Normal,
            JMClient.Assets.ClientDesignConfig.WindowState.Minimized => Avalonia.Controls.WindowState.Minimized,
            JMClient.Assets.ClientDesignConfig.WindowState.Maximized => Avalonia.Controls.WindowState.Maximized,
            JMClient.Assets.ClientDesignConfig.WindowState.FullScreen => Avalonia.Controls.WindowState.FullScreen,
            _ => Avalonia.Controls.WindowState.Normal
        };
    }

    /// <summary>
    /// 从Avalonia的WindowState转换
    /// </summary>
    private static WindowState ConvertFromAvaloniaWindowState(Avalonia.Controls.WindowState windowState)
    {
        return windowState switch
        {
            Avalonia.Controls.WindowState.Normal => JMClient.Assets.ClientDesignConfig.WindowState.Normal,
            Avalonia.Controls.WindowState.Minimized => JMClient.Assets.ClientDesignConfig.WindowState.Minimized,
            Avalonia.Controls.WindowState.Maximized => JMClient.Assets.ClientDesignConfig.WindowState.Maximized,
            Avalonia.Controls.WindowState.FullScreen => JMClient.Assets.ClientDesignConfig.WindowState.FullScreen,
            _ => JMClient.Assets.ClientDesignConfig.WindowState.Normal
        };
    }

    /// <summary>
    /// 转换为Avalonia的SystemDecorations
    /// </summary>
    private static Avalonia.Controls.SystemDecorations ConvertToAvaloniaSystemDecorations(SystemDecorations systemDecorations)
    {
        return systemDecorations switch
        {
            JMClient.Assets.ClientDesignConfig.SystemDecorations.None => Avalonia.Controls.SystemDecorations.None,
            JMClient.Assets.ClientDesignConfig.SystemDecorations.BorderOnly => Avalonia.Controls.SystemDecorations.BorderOnly,
            JMClient.Assets.ClientDesignConfig.SystemDecorations.Full => Avalonia.Controls.SystemDecorations.Full,
            _ => Avalonia.Controls.SystemDecorations.Full
        };
    }

    #endregion
    
    private static readonly MaterialThemeBase MaterialThemeStyles =
        Application.Current!.LocateMaterialTheme<MaterialThemeBase>();

    /// <summary>
    /// 这里是对窗口的主题进行管理，本项目主要使用Material主题，获取主题管理然后按官方推荐的方式进行修改即可
    /// </summary>
    /// <param name="application"></param>
    public void ApplyThemeSettings(Application application)
    { 
        var current = MaterialThemeStyles.CurrentTheme;
        if (MaterialThemeStyles.BaseTheme  == BaseThemeMode.Dark)
        { 
            MaterialThemeStyles.BaseTheme = BaseThemeMode.Light; 
        }
        else
        {
            MaterialThemeStyles.BaseTheme = BaseThemeMode.Light;
        }
        _logger.LogInformation("应用主题设置: {Theme}", CurrentConfig.Colors.BaseTheme);  
    }

    #region 测试内容 不应该考虑 这里只是提供了切换主题颜色的示范 可以参考
    /// <summary>
    /// 切换预设主题 A/B/C
    /// </summary>
    public void ApplyPresetTheme(string key)
    {  
        PrimaryColor primary = PrimaryColor.Red;
        Color primaryColor = SwatchHelper.Lookup[(MaterialColor)primary];

        SecondaryColor secondary = SecondaryColor.Teal;
        Color secondaryColor = SwatchHelper.Lookup[(MaterialColor)secondary];
        // For dark theme use  Theme.Dark; 
        IBaseTheme baseTheme = Theme.Light;

        ITheme theme = Theme.Create(baseTheme, primaryColor, secondaryColor);
        switch (key)
        {
            case "A":

                primaryColor = Color.FromArgb(123, 233, 178, 100);
                  secondaryColor = Color.FromArgb(123,233,178,100);
                  
                // For dark theme use  Theme.Dark;
                
                  baseTheme = Theme.Light;

                  theme = Theme.Create(baseTheme, primaryColor, secondaryColor);

                MaterialThemeStyles.CurrentTheme = theme ;
                MaterialThemeStyles.BaseTheme = BaseThemeMode.Dark;
                break;
            case "B":
                  primary = PrimaryColor.DeepOrange;
                  primaryColor = SwatchHelper.Lookup[(MaterialColor)primary];

                  secondary = SecondaryColor.Blue;
                  secondaryColor = SwatchHelper.Lookup[(MaterialColor)secondary];
                // For dark theme use  Theme.Dark;
                
                  baseTheme = Theme.Light;

                  theme = Theme.Create(baseTheme, primaryColor, secondaryColor);

                MaterialThemeStyles.CurrentTheme = theme ;
                MaterialThemeStyles.BaseTheme = BaseThemeMode.Light;
                break;
            case "C":
                  primary = PrimaryColor.Red;
                  primaryColor = SwatchHelper.Lookup[(MaterialColor)primary];

                  secondary = SecondaryColor.Green;
                  secondaryColor = SwatchHelper.Lookup[(MaterialColor)secondary];
                
                  baseTheme = Theme.Light;

                  theme = Theme.Create(baseTheme, primaryColor, secondaryColor);
                  MaterialThemeStyles.CurrentTheme = theme ;
                  MaterialThemeStyles.BaseTheme = BaseThemeMode.Light;
                break;
            default:
                _logger.LogWarning("未知主题标识: {Key}", key);
                return;
        }

        _logger.LogInformation("已应用主题: {Key} 模式={Mode}, 主色={Primary}, 辅色={Secondary.color}",
            key, MaterialThemeStyles.BaseTheme, MaterialThemeStyles.CurrentTheme.PrimaryLight.Color, MaterialThemeStyles.CurrentTheme.SecondaryLight.Color);
    }

    #endregion
    /// <summary>
    /// 布局配置 这里主要是对窗口的元素的布局方式进行配置，还未完善
    /// </summary>
    /// <param name="containerProvider"></param>
    public void ApplyLayoutSettings()
    {
        _logger.LogInformation("应用布局设置，共 {Count} 个模板", CurrentConfig.LayoutTemplates.Count);

        foreach (var (key, template) in CurrentConfig.LayoutTemplates)
        {
            // 这里你可以根据 template.Columns / Rows / Regions 逻辑，自定义布局解析器
            _logger.LogDebug("应用布局模板: {TemplateName}, 区域数: {RegionCount}", key, template.Regions.Count);
            // 未来扩展：从 Regions 动态设置 Prism 区域、注册 View 等
        }
    }
    // 辅助方法：将十六进制字符串转换为Color
    /// <summary>
    /// 将关于颜色的字符转为Material可以接受的类型Color
    /// </summary>
    /// <param name="hex"></param>
    /// <returns></returns>
    private static Color ParseColor(string hex)
    {
        return Color.Parse(hex.StartsWith("#") ? hex : $"#{hex}");
    }
}
